import {AuditOutlined, DeleteOutlined, EditOutlined, PlusOutlined, UsergroupAddOutlined} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, message, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import UpdateForm from './components/UpdateForm';
import { createGroup, deleteGroupById, getGroupList, updateGroup } from '@/services/groupManage';
import { history } from 'umi';
const TableList: React.FC = () => {
  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: any) => {
    try {
      await createGroup({ ...fields });
      message.success('添加成功！');
      return true;
    } catch (error) {
      if (error?.response?.data?.code == 'A1016') {
        message.error(error.response.data.message);
      } else {
        message.error('添加失败!');
      }
      return false;
    }
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: any) => {
    const params = {
      groupDesc: fields.groupDesc,
      groupName: fields.groupName,
      id: fields.id,
    };
    try {
      await updateGroup(params);
      message.success('更新成功！');
      return true;
    } catch (error) {
      message.error('更新失败！');
      return false;
    }
  };

  /**
   *  Delete node
   * @zh-CN 删除多个节点
   *
   * @param selectedRows
   */
  const handleRemove = async (record) => {
    try {
      await deleteGroupById({
        id: record.id,
      });
      message.success('已删除！');
      if (actionRef.current) {
        actionRef.current.reload();
      }
      return true;
    } catch (error) {
      message.error('删除失败！');
      return false;
    }
  };

  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.UserListItem>();

  const columns: ProColumns<API.UserListItem>[] = [
    {
      title: '部门名称',
      align: 'center',
      width: '25%',
      dataIndex: 'groupName',
    },
    {
      title: '部门说明',
      align: 'center',
      width: '35%',
      dataIndex: 'groupDesc',
    },
    {
      title: '操作',
      align: 'left',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          <Button className={'buttonMargin'} shape={'round'} type="primary" icon={<EditOutlined />}>
            编辑
          </Button>
        </a>,
        <Popconfirm title="确定是否删除?" onConfirm={() => handleRemove(record)} key="delete">
          <a style={{ color: 'red' }}>
            <Button danger className={'buttonMargin'} shape={'round'} icon={<DeleteOutlined />}>
              删除
            </Button>
          </a>
        </Popconfirm>,
        <a
          key="manage"
          style={{ color: 'gray' }}
          onClick={() => {
            history.push({
              pathname: '/memberManagement/groupNumber',
              state: {
                groupId: record.id,
              },
            });
          }}
        >
          <Button className={'buttonMargin'} shape={'round'} icon={<UsergroupAddOutlined />}>
            成员管理
          </Button>
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        // headerTitle="用户列表"
        actionRef={actionRef}
        rowKey={'id'}
        search={false}
        tableStyle={{ textAlign: 'center' }}
        options={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleUpdateModalVisible(true);
              setCurrentRow({});
            }}
          >
            <PlusOutlined />
            添加
          </Button>,
        ]}
        request={async () => {
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          const msg = await getGroupList();
          return {
            data: msg.data,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: msg.code === '0',
            // 不传会使用 data 的长度，如果是分页一定要传
            // total: number,
          };
        }}
        pagination={{ pageSize: 10 }}
        columns={columns}
      />

      <UpdateForm
        onSubmit={async (value) => {
          //判断id是否存在，判断新建/边界

          let success;
          if (!currentRow.id) {
            success = await handleAdd(value);
          } else {
            value.id = currentRow.id;
            success = await handleUpdate(value);
          }

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
        key={new Date().getTime()}
      />
    </PageContainer>
  );
};

export default TableList;
